import { FC } from 'react';
import { Upload, Button, message, Space } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { RcFile, UploadFile } from 'antd/es/upload/interface';
import './UploadAttachment.css';  // 引入自定义的 CSS 文件
import { addDocumentInfo } from '../../apis/public/fileUpDownload';
import React, { useState } from 'react';

//场景设置默认目录
const sceneEnum = {
	"chat":312810899759042560,
	"vector":312810987713597440
}

interface UploadAttachmentProps {
	scene?:string;  //适用于场景
	directory?: number; // 文件目录
	title?: string; // 附件标题
	onUploadSuccess: (res: FileRresponse) => void; // 上传成功回调函数
	customDealRequest?:(file: UploadFile) => void;
	maxFileSize?: number; // 文件大小限制，单位为字节（默认 5MB）
	accept?:string;
	showUploadList?:boolean;
	child?:any;
  dragger?: boolean //是否允许拖拽
}

interface DocumentInfo {
  id?: number;
  fileName: string;
  directoryId: number;
  file:any;
}

interface FileRresponse {
  code: number;
  msg: string;
  status: boolean;
  data: any;
  fail: boolean;
}

const UploadAttachment: FC<UploadAttachmentProps> = ({
  scene,
  directory,
  title,
  onUploadSuccess,
  customDealRequest,
  maxFileSize=20 * 1024 * 1024,
  accept=".pdf,.doc,.docx",
  showUploadList=true,
  child,
  dragger=false,
  ...rest
}) => {
  const [fileList, setFileList] = useState<UploadFile[]>([]);

  // 上传前的文件验证，确保文件类型和数量
  const beforeUpload = (file: RcFile) => {
    // 数量限制
    if (fileList.length >= 1) {
      message.error('只允许上传1个文件');
      return Upload.LIST_IGNORE;
    }
    // 类型限制
    const isValidFileType = [
      'application/pdf',
      'application/msword',
      'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
    ].includes(file.type);
    if (!isValidFileType) {
      message.error('只能上传PDF、DOC或DOCX文件');
      return Upload.LIST_IGNORE;
    }
    // 大小限制
    if (file.size > maxFileSize) {
      message.error(`文件大小不能超过 ${maxFileSize / 1024 / 1024}MB`);
      return Upload.LIST_IGNORE;
    }
    return true;
  };

  // 自定义上传方法
  const customRequest = async ({ file, onSuccess, onError }: any) => {
    if(customDealRequest){
      customDealRequest(file)
      return;
    }
    try {
      let newDirectoryId = directory?directory:0;
      if(scene&&directory===undefined){
        newDirectoryId = sceneEnum[scene]?sceneEnum[scene]:  newDirectoryId
      }
      const res = await addDocumentInfo(file,newDirectoryId)
      onUploadSuccess(res); // 调用上传成功回调函数
      // 上传成功后，手动设置fileList为done
      setFileList([{
        uid: file.uid,
        name: file.name,
        status: 'done',
        url: '',
      }]);
      if(onSuccess) onSuccess(res);
    } catch (error) {
      if(onError) onError(error);
    }
  };

  // 处理文件列表变化，只保留最新的一个
  const handleChange = (info: any) => {
    let newList = [...info.fileList];
    if (newList.length > 1) newList = [newList[newList.length - 1]];
    // 如果最新文件上传成功，强制设为 done
    if (newList[0] && newList[0].status === 'uploading' && info.event?.percent === 100) {
      newList[0].status = 'done';
    }
    setFileList(newList);
  };

  const Uploader = dragger ? Upload.Dragger : Upload;

  return (
    <div className="upload-container">
      {title&&<h3>{title}</h3>}
      <Uploader
        customRequest={customRequest}
        beforeUpload={beforeUpload}
        showUploadList={showUploadList}
        accept={accept}
        maxCount={1}
        fileList={fileList}
        onChange={handleChange}
        {...rest}
      >
        {(child ? child : (
          <Space direction="vertical">
            <Button icon={<UploadOutlined />} type="primary" className="upload-button">
              上传附件
            </Button>
          </Space>
        ))}
      </Uploader>
    </div>
  );
};

export default UploadAttachment;

